package com.kjlink.widget.monitoring.service;

import com.kjlink.widget.monitoring.entity.MonitorEventBatch;
import com.kjlink.widget.monitoring.entity.MonitorRawEvent;
import com.kjlink.widget.monitoring.repository.MonitorEventBatchRepository;
import com.kjlink.widget.monitoring.repository.MonitorRawEventRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

/**
 * 描述:
 * 处理批次  服务
 *
 * @author Vic.xu
 * @since 2025-08-05 10:54
 */
@Service
public class EventBatchService {
    private static final Logger logger = LoggerFactory.getLogger(EventBatchService.class);


    @Resource
    private MonitorRawEventRepository rawEventRepository;

    @Resource
    private MonitorEventBatchRepository batchRepository;


    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void saveInNewTransaction(MonitorEventBatch batch) {
        batchRepository.save(batch);
    }

    /**
     * 根据id查询原始事件
     */
    public MonitorRawEvent findRawEventById(String firstEventId) {
        return rawEventRepository.findById(firstEventId).orElse(null);
    }


    /**
     * 按状态分页查询，默认按创建时间倒序
     *
     * @param status 批次状态（非空）
     * @param page   页码（从0开始）
     * @param size   每页条数
     */
    public Page<MonitorEventBatch> getBatchesByStatus(
            MonitorEventBatch.BatchStatus status,
            int page,
            int size) {

        // 强制按创建时间（createTime）倒序排序
        Pageable pageable = PageRequest.of(
                page - 1,
                size,
                Sort.by(Sort.Direction.DESC, "createTime")
        );
        // 根据status是否为null选择查询方法
        if (status != null) {
            // 查询指定状态的批次（包括status为该枚举值的记录）
            return batchRepository.findByStatus(status, pageable);
        } else {
            // 查询所有批次（包括status为null的记录）
            return batchRepository.findAll(pageable);
        }
    }

    public Page<MonitorRawEvent> getRawEventByBatchNo(String batchNo, int page, int size) {
        // 强制按创建时间（createTime）倒序排序
        Pageable pageable = PageRequest.of(
                page - 1,
                size,
                Sort.by(Sort.Direction.DESC, "createTime")
        );
        // 根据status是否为null选择查询方法
        if (StringUtils.hasText(batchNo)) {
            // 查询指定批次的数据
            return batchRepository.findPageByBatchNo(batchNo, pageable);
        } else {
            // 查询所有
            return rawEventRepository.findAll(pageable);
        }
    }
}